package com.lcxw.hxzbapi.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcxw.hxzbapi.dao.mapper.VipBuyDetailMapper;
import com.lcxw.hxzbapi.entity.pojo.VipBuyDetail;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.service.VipBuyDetailService;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbcommon.common.StringUtil;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class VipBuyDetailServiceImpl extends
    ServiceImpl<VipBuyDetailMapper, VipBuyDetail> implements
    VipBuyDetailService {

    @Resource
    YwpdMemberService ywpdMemberService;

    @SneakyThrows
    @Override
    @Async
    public void checkVipBuyDetail(String orderNo) {
        QueryWrapper<VipBuyDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(VipBuyDetail::getOrderNo, orderNo);
        VipBuyDetail vipBuyDetail = getOne(queryWrapper);
        vipBuyDetail.setStatus("1");
        updateById(vipBuyDetail);
        YwpdMember ywpdMember = ywpdMemberService
            .selectYwpdMemberByUserId(vipBuyDetail.getUserId());

        ywpdMember.setVip(1);
        String vipExpire = ywpdMember.getVipExpire();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StringUtil.isEmpty(vipExpire)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            if (vipBuyDetail.getVipType().equals("month")) {
                calendar.add(Calendar.MONTH, 1);
            } else {
                calendar.add(Calendar.YEAR, 1);
            }
            Date date = calendar.getTime();

            vipExpire = sdf.format(date);

        } else {
            Date date = sdf.parse(vipExpire);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            if (vipBuyDetail.getVipType().equals("month")) {
                calendar.add(Calendar.MONTH, 1);
            } else {
                calendar.add(Calendar.YEAR, 1);
            }
            date = calendar.getTime();
            vipExpire = sdf.format(date);
        }

        ywpdMember.setVipExpire(vipExpire);
        ywpdMemberService.updateYwpdMember(ywpdMember);
    }
}
